package com.isoftstone.util.bocop;

import com.isoftstone.util.BocHttpUtil;
import com.isoftstone.util.PropertiesUtils;
import net.sf.json.JSONObject;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by as on 2017/12/20.
 */
public class BocopUtils {
    public static Logger logger = LoggerFactory.getLogger(BocHttpUtil.class);

    //封装
    public static HttpsURLConnection getHttpsURLConnect(String connectUrl, HttpServletRequest request) {
        HttpsURLConnection httpUrlConn = null;
        try {
            // 创建SSLContext对象，并使用我们指定的新人管理器初始化
            TrustManager[] tm = {new NewX509TrustManager()};
            SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
            sslcontext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocktFactory对象
            SSLSocketFactory ssf = sslcontext.getSocketFactory();
            String urls = PropertiesUtils.getProperties(connectUrl);
            URL url = new URL(urls);
            httpUrlConn = (HttpsURLConnection) url
                    .openConnection();
            //==============================================
            httpUrlConn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });
            //=================================================
            httpUrlConn.setSSLSocketFactory(ssf);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置header参数
            httpUrlConn.setRequestProperty("clentid",
                    PropertiesUtils.getProperties("clientid"));
            httpUrlConn.setRequestProperty("userid", (String) request
                    .getSession().getAttribute("userid"));
            httpUrlConn.setRequestProperty("acton", (String) request
                    .getSession().getAttribute("accessToken"));
            httpUrlConn.setRequestProperty("chnflg", "1");
            Date date = new Date();
            SimpleDateFormat d = new SimpleDateFormat("yyyyMMdd");
            SimpleDateFormat da = new SimpleDateFormat("HHmmss");
            httpUrlConn.setRequestProperty("trandt", d.format(date));
            httpUrlConn.setRequestProperty("trantm", da.format(date));
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpUrlConn;
    }

    /**
     * 获取手机验证码
     *
     * @param request
     */
    public static Map<String, String> getCode(HttpServletRequest request) {
        StringBuffer buffer = new StringBuffer();
        Map<String, String> map = new HashMap<>();
        try {
            HttpsURLConnection httpUrlConn = getHttpsURLConnect("getPhoneCode", request);
            // 当有数据需要提交时
            OutputStream outputStream = httpUrlConn.getOutputStream();
            // 注意编码格式，防止中文乱码
            JSONObject obj = new JSONObject();

            // 请求数据
            obj.element("mobleno", (String) request.getSession().getAttribute("mobleno"));
            obj.element("userid",
                    (String) request.getSession().getAttribute("userid"));
            obj.element("cardno", (String) request.getSession().getAttribute("cardno"));
            obj.element("accrem", (String) request.getSession().getAttribute("accrem"));
            outputStream.write(obj.toString().getBytes("UTF-8"));
            outputStream.close();
            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            logger.info("获取验证码接口" + buffer.toString());
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            httpUrlConn.disconnect();

            ObjectMapper mapper = new ObjectMapper();
            map = mapper.readValue(buffer.toString(), Map.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 验证码发送到boc验证正确性
     *
     * @param request
     * @return
     */

    public static String verifyCode(HttpServletRequest request) {
        StringBuffer buffer = new StringBuffer();
        Map<String, String> map = new HashMap<>();
        try {
            HttpsURLConnection httpUrlConn = getHttpsURLConnect("checkPhoneCode", request);
            // 当有数据需要提交时
            OutputStream outputStream = httpUrlConn.getOutputStream();
            // 注意编码格式，防止中文乱码
            JSONObject obj = new JSONObject();

            // 请求数据
            obj.element("chkcode", (String) request.getParameter("chkcode"));
            obj.element("usrid",
                    (String) request.getSession().getAttribute("userid"));

            outputStream.write(obj.toString().getBytes("UTF-8"));
            outputStream.close();
            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            logger.info("验证验证码 结果返回" + buffer.toString());
            //{"msgcde":"M321","rtnmsg":"短信验证不通过！[B03_00015]"}
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            httpUrlConn.disconnect();

            ObjectMapper mapper = new ObjectMapper();
            map = mapper.readValue(buffer.toString(), Map.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
//        if (map.get("usrid") != null && map.get("usrid").equals((String) request.getSession().getAttribute("userid"))) {
//            return "000000";
//        }
        if (map.get("result") != null) {
            return map.get("result");
        } else {
            return "验证失败!";
        }
    }
}

class NewX509TrustManager implements X509TrustManager {

    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }


}


